package ged.diagram.edit.parts;

import ged.diagram.part.GedDiagramEditor;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.draw2d.Animation;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gmf.runtime.common.ui.action.AbstractActionDelegate;
import org.eclipse.gmf.runtime.diagram.ui.actions.ActionIds;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeCompartmentEditPart;
import org.eclipse.gmf.runtime.diagram.ui.requests.ArrangeRequest;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PlatformUI;

public class MyLayoutActionDelegate extends AbstractActionDelegate implements IWorkbenchWindowActionDelegate {

    public static String LAYOUT_TYPE = ""; //"myLayoutType";
    
    public void setLayout_Type(String L_type){
    	LAYOUT_TYPE = L_type;
    }
    
    protected void doRun(IProgressMonitor progressMonitor) {
        EditPart parent = getParentEditPart();
        
        ArrangeRequest request = new ArrangeRequest(ActionIds.ACTION_ARRANGE_ALL, LAYOUT_TYPE);

        Command command = parent.getCommand(request);
        
        Animation.markBegin();
        
        command.execute();
        
        Animation.run(500);
    }

    public void selectionChanged(IAction act, ISelection selection) {
        super.selectionChanged(act, selection);
        
        // calculate enabled
        if (getStructuredSelection().isEmpty()) {
            getAction().setEnabled(false);
            return;
        }
        
        EditPart parent = getParentEditPart();
        
        if (parent == null) {// || !(parent.getContentPane().getLayoutManager() instanceof XYLayout)) {
            getAction().setEnabled(false);
        }
        getAction().setEnabled(true);
    }
    
    protected EditPart getParentEditPart() {
    	//if the editor is the GedDiagramEditor
    	if(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor() instanceof GedDiagramEditor)
    	{
        EditPart parent = (EditPart)((IAdaptable)getStructuredSelection().
                getFirstElement()).getAdapter(EditPart.class);
        
        while (parent != null && !(parent instanceof DiagramEditPart) && !(parent instanceof ShapeCompartmentEditPart)) {
            parent = parent.getParent();
        }
        return parent;
    	}
        return null;
    }
}